using System;
using System.Collections.Generic;
using System.Configuration;
using System.Dynamic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MySqlConnector;
using RFS.BizLogic.PaiShi.Accounting;
using RFS.BizLogic.PaiShi.Ports;
using RFS.BizLogic.Sys;
using RFS.BizLogic.Sys.impl;
using RFS.BizLogic.utils;
using RFS.Domain.Sys;
using ycx;

namespace RFS.BizLogic.Ports.Adapters
{
    public class ConfigMySqlAdapter : IConfigT
    {
        // private string configfile = "settings.json";
        ISys _sys  ;


        public ConfigMySqlAdapter(  ILog log, ISys sys)
        {
            _log = log;
            _sys = sys;

            _sys.Exited += (sender, args) => SaveCoinfig();

            _log = log;
            string connectionStringName = "CnnStrAccDb";
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
                ReadConifg();
            }
            catch (Exception e)
            {
                _log.Err(e);
            }
           
        }

        ConfigSys _config = new ConfigSys();
        
        
        private readonly ILog _log;
        private readonly string _connectionString;
        
        
        public void SaveSysConfig(ConfigSys o)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                using (var tran = connection.BeginTransaction())
                {
                    #region saving entity

                    var sql1 = $"DELETE FROM {EntityTableName} WHERE ID = {configId}";
                    using (var command = new MySqlCommand(sql1, connection, tran))
                    {
                        command.ExecuteNonQuery();
                    }


                    string sql = $@"
            INSERT INTO {EntityTableName} (id, entityJson)
            VALUES (@id, @entityJson);
        ";
                    using (var command = new MySqlCommand(sql, connection, tran))
                    {
                        command.Parameters.AddWithValue("@id", configId);
                        command.Parameters.AddWithValue("@entityJson", o.ToJson());
                        command.ExecuteNonQuery();
                    }

                    #endregion
                    tran.Commit();
                    connection.Close();
                }
            }
        }

        // const string EntityTableName { get; set; }
        private const string EntityTableName = "acc_tbl_AccSetEntityGraph";


        List<dynamic> ExecuteSqlQuery(string query)
        {
            List<dynamic> results = new List<dynamic>();


            using (MySqlConnection connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                using (MySqlCommand command = new MySqlCommand(query, connection))
                {
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            dynamic obj = new ExpandoObject();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                var fieldName = reader.GetName(i);
                                var fieldValue = reader[i];
                                ((IDictionary<string, object>)obj).Add(fieldName, fieldValue);
                            }

                            results.Add(obj);
                        }
                    }
                }
            }

            return results;
        }

        ulong configId = (ulong)99992;

        
        public ConfigSys GetSysConfig()
        {
            var res = ExecuteSqlQuery($"select * FROM {EntityTableName} WHERE ID = {configId}");
            if (res.Count() < 1) return new ConfigSys();

            var s = res.FirstOrDefault()  ;
            var config = ((string)s.entityJson ).ToObject<ConfigSys>();
            return config;
        }

        private void ReadConifg()
        {
            // if (!File.Exists(configfile)) SaveCoinfig();
            // var txt = File.ReadAllText(configfile);
            try
            {
                _config = GetSysConfig()  ;

            }
            catch (Exception e)
            {
                _log.Err(e);
            }
        }

        private void SaveCoinfig()
        {
            SaveSysConfig(_config);
        }

        public ConfigSys ConfigSys
        {
            get => _config;
        }

        public bool AlowSystemSmartChoosePrice { get; set; } = true;
        public OrderMatchingMode OrderMatchingMode { get; set; } = OrderMatchingMode.宽松;

        public void Save(ConfigSys config)
        {
            SaveCoinfig();
        }

        public void SaveIt()
        {

            SaveCoinfig();

        }
    }
}